<template>
    <div style="position: relative;">
      <div id="container"></div>
      <div class="map-tools">
        <div>
          <div class="bjk-js"><i class="iconfont icon-ic_ac_302x"></i></div>
          <div class="bjk-tz">健身</div>
        </div>
        <div>
          <div class="bjk-tb"><i class="iconfont icon-zoulu"></i></div>
          <div class="bjk-tz">徒步</div>
        </div>
        <div>
          <div class="bjk-qx"><i class="iconfont icon-ziyuan"></i></div>
          <div class="bjk-tz">骑行</div>
        </div>
        <div>
          <div class="bjk-pb"><i class="iconfont icon-paobu"></i></div>
          <div class="bjk-tz">跑步</div>
        </div>
      </div>
      <button class="bjk-sh" @click="cs">如何使用？</button>
      <div  class="bjkZone">
        <div v-if="nowstate">
          <div @click="goTo" >
            <p class="bjkaaa" >{{ runnowDistance.slice(0,5) }}</p>
            <span style="color: #8d8d8d;">运动总公里</span>
          </div>
          <div class="bjk-dyh">
            <svg t="1714370835418" class="icon"  viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3337"><path d="M763.647509 470.785079L283.648445 4.353988c-6.143988-5.887989-15.871969-5.887989-21.759957 0.511999l-14.335972 14.847971c-5.887989 6.143988-5.631989 16.127969 0.511999 22.015957l479.999064 466.431091c1.279998 1.279998 1.535997 2.815995 1.535997 3.839992 0 1.023998-0.256 2.559995-1.535997 3.839993L247.808515 982.272081c-6.143988 5.887989-6.399988 15.871969-0.511999 22.015957l14.591972 14.847971c5.887989 6.143988 15.61597 6.399988 21.759957 0.511999l479.999064-466.43109c11.263978-10.751979 17.407966-25.343951 17.407966-41.21592s-6.143988-30.207941-17.407966-41.215919z" p-id="3338" data-spm-anchor-id="a313x.search_index.0.i3.5e623a81Y0Swaa" class="selected" fill="#9d9d9d"></path></svg>
          </div>
        </div>
        <div v-if="!nowstate" class="bjk-ks" @click="bjkkaishi">开始运动</div>
        
      </div>
    </div>
  </template>
<script lang="ts" setup>

import AMapLoader from "@amap/amap-jsapi-loader";
import { onMounted,ref } from "vue";
import axios from "axios"
axios.defaults.baseURL="http://127.0.0.1:3000"
//进行编程式导航
import { useRouter } from 'vue-router';

//当前是否处于运动中
const nowstate=ref(false)

const router = useRouter();
//跳转到徒步页面
const goTo = () => {
    router.push('/mileage');
};
//当前跑步记录标题
const runtitle=ref('')
//开始运动的当前时间
const runnowData=ref("")
//当前运动距离
const runnowDistance=ref('')
//当前运动时长
const runnowTime=ref('')
//当前跑步记录的id
const runnowid=ref(null)


//开始运动时间
const starttime=ref('')
//结束运动时间
const endtime=ref('')


//结束跑步
const cs=async ()=>{
  nowstate.value=false
  //将当前运动结束的时间戳赋值给endtime
  endtime.value=JSON.stringify(new Date().getTime())
  //根据starttime和endtime计算出当前运动的总时长转换为xx分xx秒赋值给runnowTime
  runnowTime.value=JSON.stringify(new Date(JSON.parse(endtime.value)-JSON.parse(starttime.value)).toISOString().substr(11, 8))

  
  console.log(runnowTime.value);
  //将新的数据传递给后端修改
  await axios.put("/updateRun",{title:runtitle.value,distance:runnowDistance.value,duration:runnowTime.value,date:runnowData.value,id:runnowid.value})
  //清除定时器
  clearInterval(timer.value)
  //清除本地存储的坐标
  localStorage.removeItem("lng")
  localStorage.removeItem("lat")
 
  //消息提示以结束运动
 console.log('运动结束');
 
}

//定时器实例
const timer=ref()

//开始记录
const bjkkaishi=async ()=>{
  //将当前运动的时间戳赋值给starttime
  starttime.value=JSON.stringify(new Date().getTime())
  



  nowstate.value=true
  //获取当前事件戳赋值给runtitle
  runtitle.value=JSON.stringify(new Date().getTime())
  //将获取当前时间转换为年月日的形式赋值给runnowDate
  runnowData.value=new Date().toLocaleDateString()
  //将当前跑步记录存放到后端
  await axios.post("/addRun",
  {title:runtitle.value,distance:runnowDistance.value,duration:runnowTime.value,date:runnowData.value})
  //根据当前跑步标题获取当前跑步记录的id
  const {data}=await axios.get("/getRun",{params:{title:runtitle.value}})
  //将当前跑步记录的id赋值
  runnowid.value=data.runs[0]._id
  // console.log(runnowid.value);
  
  timer.value=setInterval(()=>{
    dwgddt(amap.value)
  },1000)
}


onMounted(()=>{
  mapshow()
})

//获取坐标点
// const getzb=async(AMap:any)=>{
//   const {data}=await axios.get("/getzb")
//   console.log(data.zb);
//   let zb:any=[]
//   console.log(data.zb.filter((items:any)=>{JSON.stringify(items.run)==runnowid.value}));
  
//   data.zb.filter((items:any)=>{JSON.stringify(items.run)==runnowid.value}).forEach((item:any)=>{
//     zb.push([item.lng,item.lat])
//   })
//   zblist=zb
//   console.log(zblist);
//   //获取到坐标后进行路线绘制
//   hzgddt(AMap)
// }

//将当前定位点坐标添加到后端服务器
const dwzbadd=async(lng:number,lat:number,AMap:any)=>{
  //读取本地存储的坐标与当前坐标进行比较
  const lng1=JSON.parse(localStorage.getItem("lng") as string)
  const lat1=JSON.parse(localStorage.getItem("lat") as string)
  //如果当前坐标与本地存储的坐标不一致则将当前坐标存入后端服务器
  if(lng!=lng1||lat!=lat1){
    await axios.post("/addzb",{lng:lng,lat:lat,run:runnowid.value})
    const {data}=await axios.get("/getzb",{params:{run:runnowid.value}})
    console.log('添加数据了');
    
    console.log(data.zb);
    let zb:any=[]
    data.zb.forEach((item:any)=>{
      zb.push([item.lng,item.lat])
    })
    zblist=zb
    console.log(zblist);
    //获取到坐标后进行路线绘制
    hzgddt(AMap)
  }
    //将当前坐标存储在本地
    localStorage.setItem("lng",JSON.stringify(lng))
    localStorage.setItem("lat",JSON.stringify(lat))
  // getzb(AMap)
    
}
var zblist:any=[]//所有定位点数组
let map=ref(null)//地图实例
let amap=ref(null)//
const jl=ref(0)//跑过的距离

//计算各个坐标点之间的距离之和
const zbdistance=(AMap:any)=>{
  for(let i=0;i<zblist.length-1;i++){
    jl.value=jl.value+AMap.GeometryUtil.distance(zblist[i],zblist[i+1])
  }
  //将当前运动距离赋值给当前跑步记录的距离并转换为公里值保留两位小数
  runnowDistance.value=JSON.stringify(jl.value/1000)
  console.log(runnowDistance.value);
  
}
//进行定位操作
const dwgddt=(AMap:any)=>{
      //  进行高精定位
      AMap.plugin('AMap.Geolocation',function(){
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：5s
            buttonPosition:'LT',    //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: false,   //定位成功后是否自动调整地图视野到定位点
            showCircle:false,   //不显示定位精度圆
            convert:true,    //将定位结果转换为高德地图坐标
            showButton:false,   //显示定位按钮
            position: "RT", //定位按钮的停靠位置
        })
        map.value.addControl(geolocation);
        geolocation.getCurrentPosition(function(status:any,result:any){
        
        if(status=='complete'){
            onComplete(result)
        }else{
            onError(result)
        }
    });
      })
      function onComplete(data:any) {
        //将获取道的定位坐标转换为高德坐标
      
        dwzbadd(data.position.lng,data.position.lat,amap.value)
        // var point1 = new AMap.LngLat(zblist[0][0], zblist[0][1]); // 北京天安门坐标
        // var point2 = new AMap.LngLat(zblist[1][0], zblist[1][1]); // 上海外滩坐标
        zbdistance(amap.value)
      }
      //解析定位错误信息
      function onError(data:any) {
          console.log('定位失败',data);
      }
}
//进行折线绘制
const hzgddt=(AMap:any)=>{
   //进行折线绘制
      AMap.plugin("AMap.Polyline",function(){
        var polyline = new AMap.Polyline({
            path: zblist,
            strokeColor: "#3366FF",  //线颜色
            strokeOpacity: 1,     //线透明度
            strokeWeight: 8,      //线宽
            strokeStyle: "solid",   //线样式
            strokeDasharray: [10, 5], //补充线样式
            lineJoin: 'round',   //折线拐点连接处样式
            lineCap: 'round',    //折线两端线帽样式
        })
        map.value.add(polyline);
      })
}

//进行地图渲染
const mapshow=()=>{
  //获取后端坐标点

  AMapLoader.load({
    key: "	eccde469bdc8203fd3b6cba1a9e58cb3", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
  })
    .then((AMap) => {
      map.value = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 18, // 初始化地图级别
      });
      amap.value=AMap
      // dwgddt(amap.value)
      // hzgddt(amap.value)

      // getzb(AMap)
      })
    .catch((e) => {
      console.log(e);
    });
}


</script>
<style scoped>
.bjk-ks{
  font-size: 20px;
  margin-top: 15px;

}
.bjkaaa{
  width: 100%;
  text-align: center;
  font-size: 25px;
  font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}
  #container {
    width: 100%;
    height: 600px;
  }
  
  .map-tools {
    position: fixed;
    top: 472px;
    width: 100%;
    height: 128px;
    z-index: 1000;
    display: flex;
    justify-content: space-around;
    background-color: #d7d7d7;
    background-color: rgba(214, 214, 214, 0.9);
    padding: 15px 0;
    box-sizing: border-box;
  }
  
  .bjk-js {
    width: 70px;
    height: 70px;
    background-color: #dcf2ff;
    border-radius: 50%;
  }
  
  .bjk-tb {
    width: 70px;
    height: 70px;
    background-color: #dcfbf3;
    border-radius: 50%;
  }
  
  .bjk-qx {
    width: 70px;
    height: 70px;
    background-color: #fff5df;
    border-radius: 50%;
  }
  
  .bjk-pb {
    width: 70px;
    height: 70px;
    background-color: #feebdd;
    border-radius: 50%;
  }
  
  .bjk-tz {
    font-size: 14px;
    width: 100%;
    margin-top: 10px;
    text-align: center;
  }
  
  .icon-ic_ac_302x {
    font-size: 50px;
    margin-top: 10px;
    margin-left: 10px;
    line-height: 70px;
    color: #0195fa;
  }
  
  .icon-zoulu {
    font-size: 50px;
    margin-top: 10px;
    margin-left: 10px;
    line-height: 70px;
    color: #00da9a;
  }
  
  .icon-ziyuan {
    font-size: 50px;
    margin-top: 10px;
    margin-left: 10px;
    line-height: 70px;
    color: #ffb200;
  }
  
  .icon-paobu {
    font-size: 80px;
    margin-top: 10px;
    margin-left: -5px;
    line-height: 70px;
    color: #fe4a00;
  }
  
  .bjk-sh {
    width: 30%;
    height: 30px;
    background-color:rgb(66, 174,62);
    border-radius: 20px;
    color: #fff;
    border: none;
    border-color: #fff;
    position: fixed;
    top: 428px;
    text-align: center;
    left: 125px;
    font-size: 13px;
    /* border: 1px solid red; */
    /* outline: none */
  }
  
  .bjkZone {
    position: fixed;
    top: 250px;
    left: 100px;
    width: 170px;
    height: 70px;
    background-color: #fff;
    border-radius: 35px;
    box-sizing: border-box;
    padding: 5px;
    display: flex;
    justify-content: center;
    font-size: 14px;
  }
 
  .bjk-dyh{
    position: absolute;
    width: 20px;
    height: 20px;
    top: 14px;
    left: 140px;
    font-size: 30px;
  }

  .middle{
    /* border: 1px solid red; */
    width: 200px;
  }
  </style>